package view.adminUser
{
	import business.AdminUserDelegate;
	
	import com.adobe.crypto.MD5;
	
	import events.MyLogEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import model.AdminUserVO;
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.containers.Canvas;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.CheckBox;
	import mx.controls.DataGrid;
	import mx.controls.LinkButton;
	import mx.controls.TextInput;
	import mx.core.Application;
	import mx.events.CloseEvent;
	import mx.events.DropdownEvent;
	import mx.events.ListEvent;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	import util.UtileFunc;

	[Bindable]
	public class AdminUserClass extends VBox
	{
		
        public var searchModes:ArrayCollection = new ArrayCollection(
            [ {label:"用户ID", data:0},
              {label:"用户名", data:1}, 
            ]);
            
		public var page:int;
		public var tips:String;
		public var pageIndices:Array;
		public var pagecnt:int;
		
		private var adminUserDelegate:AdminUserDelegate;
		
		//view 
		public var permissionBox:VBox;   
		public var userId:TextInput;
		public var username:TextInput;
		public var password:TextInput;
		public var confirmPassword:TextInput;
		public var isSuper:CheckBox;
		public var audti:CheckBox;   
		public var applyClass:CheckBox;	
		public var user:CheckBox;   	
		public var game:CheckBox;   	
		public var cms:CheckBox;   	
		public var msg:CheckBox;   	
		public var activity:CheckBox;   
		public var adminUser:CheckBox;  
		public var item_search_input:TextInput; 
		public var admimUserGrid:DataGrid;	
		public var log:CheckBox;
		public var user_money:CheckBox;
		public var applyPay:CheckBox;
		public var finance:CheckBox;
        
        private var _m_items:ArrayCollection;   
        private var logId:String = '-1'; 	
		
		public function AdminUserClass()
		{
			super();
			
			adminUserDelegate = new AdminUserDelegate(this);
			this.addEventListener("dataReflesh",makePageIndices);
		}
		
		public function init():void
		{
			getPage(0);
		}
		
		public function onRefreshClick():void
		{
			getPage(page);
		}
		
		public function getPage(page:int=0):void
		{
			this.adminUserDelegate.getUser(page);	
		}
		
		public function getUserResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if(result.code == 0)
			{
				this.page = result.page>0?result.page:0;
				this.pagecnt = result.pagecnt>1?result.pagecnt:1;				
				var backData:Array = result.data as Array;
				for each(var data:Object in backData)
				{
					formatData(data);
				}
				this.m_items = new ArrayCollection(backData);				
			}
			else
			{
				tips = '<font color="#FF0000">获取资源失败失败</font>';
				Alert.show(result.msg);					
			}			
		}
		
		private function formatData(obj:Object):void
		{
			var createTime:Date = new Date();
			createTime.setTime(Number(obj.createTime)*1000);
			obj.createTime = createTime;
			
			var lastTime:Date = new Date();
			lastTime.setTime(Number(obj.lastTime)*1000);
			obj.lastTime = lastTime;			
			
			obj.isSuper = obj.isSuper=='1'?true:false;
			
		}		
		
		public function onSearch(type:int):void
		{
			var searchObj:Object = new Object();
			if(type == 0)
			{
				//id
				if(!item_search_input.text)
				{
					tips = '<font color="#FF0000">请输入要查找的用户ID</font>';
					return ;
				}
				searchObj.id = int(item_search_input.text);
			}	
			else if(type == 1)
			{
				//title
				if(!item_search_input.text)
				{
					tips = '<font color="#FF0000">请输入要查找的用户名</font>';
					return ;
				}				
				searchObj.name = String(item_search_input.text);
			}
			
			adminUserDelegate.search(searchObj);		
		}
		
		public function searchResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				var backData:Array = result.data as Array;
				for each(var data:Object in backData)
				{
					formatData(data);
				}
				this.m_items = new ArrayCollection(backData);
				
			}
			else
			{
				tips = '<font color="#FF0000">用户查找失败</font>';
				Alert.show(result.msg);				
			}
		}		
		
		public function get m_items():ArrayCollection
		{
			return this._m_items;
		}		
		
		public function set m_items(value:ArrayCollection):void
		{
			_m_items = value;
			dispatchEvent(new Event('dataReflesh'));
		}		
		
		public function closeEventHandle(event:DropdownEvent):void
		{
			/* if(ComboBox(event.target).selectedItem.data == 2)
			{
				searchInputStack.selectedIndex = 1
			}
			else
			{
				searchInputStack.selectedIndex = 0;
			} */
		}
		
		private function makePageIndices(event:Event=null):void
		{
			var a:Array = new Array();
			a.push({page:0,desc:'首页'});			
			a.push({page:page-1,desc:'前一页'});			
			a.push({page:page+1,desc:'后一页'});
			a.push({page:pagecnt-1,desc:'尾页'});
			this.pageIndices = a;
		}
		
		public function addUserHandle(event:Event):void
		{
			if(password.text.length <= 0)
			{
				Alert.show('密码不能为空','提示');
				return ;				
			}
			else if(String(password.text) != String(confirmPassword.text))
			{
				Alert.show('两次输入的密码不一样','提示');
				return ;
			}
			
			var addObj:Object = new Object();
			addObj.name = String(username.text);
			addObj.password = MD5.hash(String(password.text));
			addObj.createTime = new Date().getTime()/1000;
			addObj.isSuper = isSuper.selected?'1':'0';
			
			addObj.permission = '';
			addObj.permission += audti.selected?'1':'0';
			addObj.permission += applyClass.selected?'1':'0';   //current add module
			addObj.permission += user.selected?'1':'0';
			addObj.permission += game.selected?'1':'0';
			addObj.permission += cms.selected?'1':'0';
			addObj.permission += msg.selected?'1':'0';
			addObj.permission += activity.selected?'1':'0';
			addObj.permission += adminUser.selected?'1':'0';
			addObj.permission += log.selected?'1':'0';   //last add module
			
			addObj.permission += user_money.selected?'1':'0';
			addObj.permission += applyPay.selected?'1':'0';
			addObj.permission += finance.selected?'1':'0';
			
			LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goAddUser);
			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ADMINUSER, LogUtil.ADD, addObj);
			//adminUserDelegate.addUser(addObj);
			
		}
		
		private function goAddUser(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goAddUser);
			this.logId = event.logId;
			adminUserDelegate.addUser(event.record);
		}
		
		public function addUserResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				tips = '<font color="#FF000">新用户(id='+result.id+')添加成功</font>';
				LogUtil.getInstance().setOptSuccessd(logId);
			}
			else
			{
				tips = '<font color="#FF0000">用户添加失败</font>';
				Alert.show(result.msg);
			}		
		}
		
		public function updateUserHandle(event:Event):void
		{
			update();
		}
		
		public function delUserHandle(event:Event):void
		{
 			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.buttonWidth = 50;
			Alert.buttonHeight = 20;

			Alert.show('确定删除这个用户吗？',
				'提示',Alert.YES | Alert.NO,null,onDelConfirmed,null,Alert.NO); 
		}
		
		private function onDelConfirmed(event:CloseEvent):void
		{
			if (event.detail==Alert.YES)
			{
				//this.adminUserDelegate.delUserById(int(userId.text));
				LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goDelUserById);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ADMINUSER, LogUtil.DEL, userId.text);				
			}			
		}
		
		private function goDelUserById(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goDelUserById);
			this.logId = event.logId;
			this.adminUserDelegate.delUserById(int(event.record));
		}
		
		public function delUserByIdResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				refleshDisplayingData(result.id,'del');
				tips = '<font color="#FF000">用户删除成功</font>';	
				LogUtil.getInstance().setOptSuccessd(this.logId);					
			}
			else
			{
				tips = '<font color="#FF0000">用户删除失败</font>';
				Alert.show(result.msg);				
			}
		}
		
		public function onDataGridItemClick(event:ListEvent):void
		{
			//set permission
			var ss:String = event.itemRenderer.data.permission as String;
			var pa:Array = UtileFunc.spliteStr2Array(ss);
			
			audti.selected = pa[0]=='1'?true:false;
			applyClass.selected = pa[1]=='1'?true:false;
			user.selected = pa[2]=='1'?true:false;
			game.selected = pa[3]=='1'?true:false;
			cms.selected = pa[4]=='1'?true:false;
			msg.selected = pa[5]=='1'?true:false;
			activity.selected = pa[6]=='1'?true:false;
			adminUser.selected = pa[7]=='1'?true:false;
			log.selected = pa[8]=='1'?true:false;
			
			user_money.selected = pa[9]=='1'?true:false;
			applyPay.selected = pa[10]=='1'?true:false;
			finance.selected = pa[11]=='1'?true:false;
			
			//set passwrod null
			password.text = '';
			confirmPassword.text = '';
			
		}
		
		public function gotoPage(page:String):void
		{
			if (page.length>0)
			{
				getPage(int(page)-1);
			}
		}
		
		public function goto(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.page;
			getPage(page);
		}
		
		public function updatePassword(oldPassword:String, newPassword:String, newConfirmPassword:String):void
		{
			if(MD5.hash(oldPassword) != ModelLocator.getInstance().adminUserVO.password)
			{
				tips = '<font color="#FF0000">旧密码输入错误！</font>';
				return ;
			}
			if(newPassword.length <= 0)
			{
				tips = '<font color="#FF0000">必须输入密码!</font>';
				return ;				
			}
			else if(newPassword != newConfirmPassword)
			{
				tips = '<font color="#FF0000">两次输入的新密码不一样！</font>';
				return ;
			}
			else
			{
				var obj:Object = new Object();
				obj.id = ModelLocator.getInstance().adminUserVO.id;
				obj.password = MD5.hash(newPassword);
				
				LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goUpdate);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ADMINUSER, LogUtil.UPDATE ,obj);
				//adminUserDelegate.update(obj);
			}			
		}
		
		public function update():void
		{
			if(password.text.length > 0)
			{
				if(String(password.text) != String(confirmPassword.text))
				{
					Alert.show('两次输入的密码不一样','提示');
					return ;
				}
			}
			
			var updateObj:Object = new Object();
			updateObj.id = int(userId.text);
			updateObj.name = String(username.text);
			
			if(password.text)
			{
				updateObj.password = MD5.hash(String(password.text));
			}
			
			updateObj.isSuper = isSuper.selected?'1':'0';
			
			updateObj.permission = '';
			updateObj.permission += audti.selected?'1':'0';
			updateObj.permission += applyClass.selected?'1':'0';   //currentAdd module
			updateObj.permission += user.selected?'1':'0';
			updateObj.permission += game.selected?'1':'0';
			updateObj.permission += cms.selected?'1':'0';
			updateObj.permission += msg.selected?'1':'0';
			updateObj.permission += activity.selected?'1':'0';
			updateObj.permission += adminUser.selected?'1':'0';
			updateObj.permission += log.selected?'1':'0';   //lastAdd module
			
			updateObj.permission += user_money.selected?'1':'0';
			updateObj.permission += applyPay.selected?'1':'0';
			updateObj.permission += finance.selected?'1':'0';
			
			LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goUpdate);
			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.ADMINUSER, LogUtil.UPDATE ,updateObj); 
			
			//this.adminUserDelegate.update(updateObj);
		}
		
		private function goUpdate(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goUpdate);
			this.logId = event.logId;
			this.adminUserDelegate.update(event.record);
		}
		
		public function updateResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if(result.code == 0)
			{
				if(!ModelLocator.getInstance().adminUserVO.isSuper)
				{
					ModelLocator.getInstance().adminUserVO.password = result.data.password;
					tips = '<font color="#FF000">成功修改密码</font>';
				}
				else
				{
					refleshDisplayingData(result.data);
					if(ModelLocator.getInstance().adminUserVO.id == result.data.id)
					{
						ModelLocator.getInstance().adminUserVO = new AdminUserVO(result.data);
						Application.application.welcomeTips.htmlText = '管理员：<b><font color="#FF0000">'+ ModelLocator.getInstance().adminUserVO.name + '</b></font>';
					}
					tips = '<font color="#FF000">成功修改用户资料</font>';
				}
				if(logId != '-1')
				{
					LogUtil.getInstance().setOptSuccessd(this.logId);
					logId = '-1';
				}
			}
			else
			{
				if(!ModelLocator.getInstance().adminUserVO.isSuper)
				{				
					tips = '<font color="#FF0000">修改密码失败！</font>';
				}
				else
				{
					tips = '<font color="#FF0000">修改资料失败！</font>';
				}	
				Alert.show(result.msg);			
			}
		}
		
		public function refleshDisplayingData(data:*,method:String='get'):void
		{
			var itemIndex:int;
			for each(var item:Object in m_items)
			{
				if(method == 'get')
				{
					if(item.id == userId.text)
					{
						formatData(data);
						
						itemIndex = m_items.getItemIndex(item);
						m_items.removeItemAt(itemIndex);
						m_items.addItemAt(data, itemIndex);		
						
						admimUserGrid.selectedItem = data;			
					}
				}
			}
			
			if(method == 'del')
			{
				if(data == userId.text)
				{
					var delItem:Object;
					for each(var item1:Object in m_items)
					{
						if(data == item1.id)
						{
							delItem = item1;
						}	
					}
					itemIndex = m_items.getItemIndex(delItem);
					m_items.removeItemAt(itemIndex);						
				}
			} 
			
		}		
		
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
	}
}